package com.xr.blog.controller;

import com.xr.blog.exception.CustomException;
import com.xr.blog.tools.Result;
import com.xr.blog.tools.ValidatorUtils;
import com.xr.blog.tools.constant.Code;
import com.xr.blog.tools.storage.OSSFactory;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 文件上传控制器
 *
 * @author XRJ
 * @email 1033835209@qq.com
 * @date 2020-08-28 16:49:38
 */
@RestController
@RequestMapping("/squirrelblog")
public class UploadController {


    /**
     * 上传图片
     * @return
     */
    @PostMapping(value = "/upload/uploadImage",produces = "application/json;charset=UTF-8")
    public Result uploadImage(MultipartFile image){
        ValidatorUtils.isNull(image,"上传的图片不能为空");
        if(!image.getContentType().contains("image")){
            throw new CustomException("文件格式错误", Code.SC_PRECONDITION_FAILED.getState());
        }
        //上传文件
        String suffix = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf("."));
        Result result=new Result();
        try {
            //判断图片是否较大，超过阈值进行压缩
            if(image.getSize()>Code.COMPRESSION_SIZE){
                Thumbnails.Builder builder=Thumbnails.of(image.getInputStream());
                //经测试，png格式图片无法正确压缩，若格式为png，则转换成jpg
                final boolean suffixIsPng=".png".equals(suffix);
                if(suffixIsPng){
                    builder.outputFormat("jpg");
                    suffix=".jpg";
                }
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                builder.scale(1f).outputQuality(0.5f).toOutputStream(bytes);
                String url= OSSFactory.build().uploadSuffix(bytes.toByteArray(), suffix);
                result.setData(url);
            }else{
                String url = OSSFactory.build().uploadSuffix(image.getBytes(), suffix);
                result.setData(url);
            }
            result.setMessage("图片上传成功");
            result.setCode(Code.SC_OK.getState());
        } catch (IOException e) {
            result.setMessage("图片上传失败");
            result.setCode(Code.UPLOAD_ERROR);
        }
        return result;
    }
}
